package com.shop.dao;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;


import java.sql.*;
import java.util.List;

public abstract class BaseDao<T> {

    private static final Logger LOGGER =Logger.getLogger(BaseDao.class);
    private static QueryRunner qr;
    protected Connection connection;
    protected PreparedStatement pstm;

    static {
        qr= new QueryRunner();
    }

    public List<T> getResultList(String sql,Object clazz,Object...params) throws SQLException {
        connection =DataSourceUtil.openConnection();
        List<Object> list = qr.query(connection,
                sql,
                params,
                new BeanListHandler<>(clazz.getClass()));
        DataSourceUtil.closeConnection(connection);
        return (List<T>)list;
    }

    public  T getResult(String sql,Object clazz,Object...params) throws SQLException {
        Object obj= qr.query( DataSourceUtil.openConnection(),
                sql,
                params,
                new BeanHandler<>(clazz.getClass()));
        DataSourceUtil.closeConnection(connection);
        return (T) obj;
    }

    public Object getObject(String sql,Object clazz,Object...params) throws SQLException {
        Object obj= qr.query( DataSourceUtil.openConnection(),
                sql,
                params,
                new BeanHandler<>(clazz.getClass()));
        DataSourceUtil.closeConnection(connection);
        return obj;
    }

    public int executeUpdate(String sql ,Object...params) throws SQLException {
        connection =DataSourceUtil.openConnection();
        int res = qr.update(connection,sql,params);
        DataSourceUtil.closeConnection(connection);
        return res;
    }
}
